<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Post\AuditFail;
use App\Admin\Actions\Post\AuditOk;
use App\Store;
use App\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Collection;

class StoreController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商户';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User());

        $grid->model()->where('type', 1)->where('merchant_status', 1)->whereNull('frozen_date')->orderBy('id', 'desc')->collection(function(Collection $collection){
            //门店数量
            $store = \DB::table('stores_info')->groupBy('uid')->pluck(\DB::raw('count(*)'), 'uid');
            $doorStore = \DB::table('stores')->groupBy('uid')->pluck(\DB::raw('count(*)'), 'uid');

            //任务量
            $subIng = \DB::table('subsidy')->where('status', 1)->groupBy('uid')->pluck(\DB::raw('count(*)'), 'uid');
            $subAll = \DB::table('subsidy')->groupBy('uid')->pluck(\DB::raw('count(*)'), 'uid');

            //过期时间
            $subStatus = \DB::table('subsidy')->orderBy('overdue', 'asc')->distinct()->pluck('overdue', 'uid');

            foreach ($collection as $item) {
                $item->store = (isset($store[$item->id])?$store[$item->id]:'0')."/".(isset($doorStore[$item->id])?$doorStore[$item->id]:0);
                $item->subCount = (isset($subIng[$item->id])?$subIng[$item->id]:'0')."/".(isset($subAll[$item->id])?$subAll[$item->id]:0);
                $ids = \DB::table('subsidy')->where('uid', $item->id)->pluck('id');
                $item->sellNum = \DB::table('users_orders')->whereIn('sub_id', $ids)->count();
                $item->statusValue = (isset($subIng[$item->id]) ?'在线':'过期') . '/'. (isset($subStatus[$item->id]) ?$subStatus[$item->id]:'--');
            }

            return $collection;
        });

        $grid->filter(function($filter) {

            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // 设置datetime类型
            $filter->like('id', '商户id');
            $filter->like('phone', '联系人电话');
            $filter->between('last_login', '登录时间')->datetime();
            $filter->where(function($query){
                switch ($this->input) {
                    case '1':
                        $query->whereHas('subsidy', function($query){
                            $query->where('status', 1);
                        });
                        break;
                    case '2':
                        $query->whereDoesntHave('subsidy', function($query){
                            $query->where('status',  1);
                        });
                        break;
                }
            }, '状态')->radio([
                '' => 'All',
                '1' => '在线',
                '2' => '过期',
            ]);
        });

        $grid->column('id', '商户ID');
        $grid->column('name', '联系人');
        $grid->column('phone', '联系电话');
        $grid->column('store', '店铺/门店');
        $grid->column('subCount', '进行中/总任务');
        $grid->column('sellNum', '累计销量');
        $grid->column('statusValue', '任务状态/过期时间');
        $grid->column('last_login', '最近登录时间');
        $grid->column('subList', '任务列表')->display(function ($title) {
            $url = '/admin/subsidies?merchant[id]='.$this->id;
            return "<a href='{$url}'>查看列表</a>";

        });

        $states = [
            'on'  => ['value' => 1, 'text' => '立即禁用', 'color' => 'primary'],
            'off' => ['value' => 5, 'text' => '立即启用', 'color' => 'default'],
        ];
        $grid->column('merchant_use_status', '是否禁用')->switch($states);

        $grid->column('storeList', '店铺列表')->display(function ($title) {
            $url = '/admin/user-stores?uid='.$this->id;
            return "<a href='{$url}'>列表</a>";

        });
        // ->modal('店铺列表', function ($model) {

            // $data = $model->stores()->take(20)->get()->map(function ($data) {
            //     return $data->only(['id']);
            // });
            // $data = $data->toArray();
            // if( count($data) ){
            //     foreach ($data as $k=>$datum) {
            //         $mei = \DB::table('stores_info')->where('store_id', $datum['id'])->where('type', 1)->first();
            //         $e = \DB::table('stores_info')->where('store_id', $datum['id'])->where('type', 2)->first();
            //         $data[$k]['title'] = "门店".($k+1);
            //         $data[$k]['meituan'] = $mei ? $mei->title :"未设置";
            //         $data[$k]['ele'] = $e ? $e->title : "未设置";
            //         $data[$k]['do'] = "<a href='"."user-stores/".$datum['id']."'>编辑</a>";
            //         unset($data[$k]['id']);
            //     }
            //     return new Table(['门店', '美团', '饿了么', '操作'], $data);
            // }
        // });

        $grid->actions(function ($actions) {

            // 去掉删除
            $actions->disableDelete();

            // 去掉编辑
            $actions->disableEdit();


        });
        return $grid;
    }

    /**
     * 待审核
     * @param Content $content
     * @return Content
     */
    public function notAudit(Content $content): Content
    {
        $grid = new Grid(new User());

        $grid->model()->where('type', 1)->whereIn('merchant_status', [0, 2])->whereHas('stores')->orderBy('id', 'desc');

        $grid->model()->collection(function(Collection $collection){
//            任务统计
            $subIng = \DB::table('subsidy')->groupBy('uid')->pluck(\DB::raw('count(*)'), 'uid');

            foreach ($collection as $item) {
                $item->statusValue = (isset($subIng[$item->id]) ?'有':'无');
            }

            return $collection;
        });

        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->where(function($query){
                $query->where('id', 'like', "%{$this->input}%")->whereOr('phone', 'like', "%{$this->input}%");
            }, '商户ID/联系人电话');
            $filter->between('merchant_date', '入驻日期')->datetime();
            $filter->between('last_login', '登录日期')->datetime();
            $filter->where(function ($query) {
                switch ($this->input) {
                    case 'yes':
                        // custom complex query if the 'yes' option is selected
                        $query->has('subsidy');
                        break;
                    case 'no':
                        $query->doesntHave('subsidy');
                        break;
                }
            }, '任务状态', 'is_have_sub')->radio([
                '' => 'All',
                'yes' => '已发任务',
                'no' => '未发任务',
            ]);

        });

        $grid->column('id', '商户ID');
        $grid->column('name', '联系人');
        $grid->column('phone', '联系电话');
        $grid->column('merchant_date', '入驻时间');
        $grid->column('last_login', '最近登录时间');
        $grid->column('statusValue', '任务状态');
        $grid->column('merchant_status', '状态')->display(function($value){
            $arr = ['待审核', '通过', '未通过'];
            return $arr[$value];
        });
        $grid->column('storeList', '店铺列表')->display(function ($title) {
            $url = '/admin/user-stores?uid='.$this->id;
            return "<a href='{$url}'>列表</a>";

        });
        $grid->actions(function ($actions) {

            // 去掉删除
            $actions->disableDelete();

            // 去掉编辑
            $actions->disableEdit();
            $actions->disableView();

            $actions->add(new AuditOk());
            $actions->add(new AuditFail());

            // 审核通过
//            $actions->append('<a href="#" class="grid-editable-remark editable editable-click" data-type="text" data-pk="'.$row->id.'" data-url="http://le.letao.com/admin/stores/auditOk/'.$row->id.'" data-value="审核通过">审核通过</a>');
        });

        return $content
            ->title('待审核')
            ->description('待审核')
            ->body($grid);
    }

    /**
     * 未联系
     * @param Content $content
     * @return Content
     */
    public function notLink(Content $content): Content
    {
        $grid = new Grid(new User());

        $grid->model()->where('type', 1)->whereIn('merchant_status', [0, 2])->whereDoesntHave('stores')->orderBy('id', 'desc');

        $grid->filter(function($filter){
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            $filter->where(function($query){
                $query->where('id', 'like', "%{$this->input}%")->whereOr('phone', 'like', "%{$this->input}%");
            }, '商户ID/联系人电话');
            $filter->between('merchant_date', '入驻日期')->datetime();
            $filter->between('last_login', '登录日期')->datetime();
            $filter->in('is_link', '联系状态')->multipleSelect(['未联系','已联系']);

        });

        $grid->column('id', '商户ID');
        $grid->column('name', '联系人');
        $grid->column('phone', '联系电话');
        $grid->column('merchant_date', '入驻时间');
        $grid->column('last_login', '最近登录时间');
        $grid->column('is_link', '状态')->display(function($value){
            $arr = ['未联系', '已联系'];
            return $arr[$value];
        });
//        $grid->setResource('updateRemark');
        $grid->column('remark', '备注')->editable()->display(function($value){
            return ($this->link_time?$this->link_time.'<br>':''.'<br>').$value;
        });
        // 全部关闭
        $grid->disableActions();
        return $content
            ->title('未联系')
            ->description('未联系')
            ->body($grid);
    }

    /**
     * 联系备注
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateRemark(): \Illuminate\Http\JsonResponse
    {
        \DB::table('users')->where('id', request()->input('pk'))->update(['link_time'=>date('Y-m-d H:i:s'),'remark'=>request()->input('value'), 'is_link'=>1]);
        return \response()->json([
                'display'=> [],
                'message'=> "更新成功 !",
                'status'=> true,
        ]);

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('name', '名称');
        $show->field('phone', '手机号');
        $show->field('merchant_date', '成为商户时间');
        $show->field('last_login', '上次登录时间');
        $show->gender()->using(['0'=>'保密','1' => '男', '2' => '女']);
        $show->avatar()->image();
        $show->storeNum('门店数')->unserialize('storeNum');
        $show->storeInfoNum('外卖店铺数')->unserialize('storeInfoNum');
        $show->divider();

        $show->storeOrderNum('累计订单数')->unserialize('storeOrderNum');
        $show->returnAmount('累计返现')->unserialize('returnAmount');
        $show->payAllAmount('用户实付')->unserialize('payAllAmount');

        $show->divider();
        $show->notSettleAmount('待结算金额')->unserialize('notSettleAmount');
        $show->notSettleNum('待结算订单')->unserialize('notSettleNum');
        $show->field('frozen_date', '结算延期日期');
        $show->field('remark', '备注');
        $show->field('link_time', '备注时间');

        $show->divider();
        $show->todayPayAllAmount('今日用户实付')->unserialize('todayPayAllAmount');
        $show->tomoPayAllAmount('昨日用户实付')->unserialize('tomoPayAllAmount');
        $show->todayReturnAmount('今日返现金额')->unserialize('todayReturnAmount');
        $show->tomoReturnAmount('昨日返现金额')->unserialize('tomoReturnAmount');
        $show->todayStoreOrderNum('今日订单数量')->unserialize('todayStoreOrderNum');
        $show->tomoStoreOrderNum('昨日订单数量')->unserialize('tomoStoreOrderNum');

        $show->panel()
            ->tools(function ($tools) {
                $tools->disableEdit();
                $tools->disableList();
                $tools->disableDelete();
            });;

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        if( request()->input('name') == 'remark' && request()->input('_editable') == 1 ){
            \DB::table('users')->where('id', request()->input('pk'))->update(['link_time'=>date('Y-m-d H:i:s')]);
        }
        $form = new Form(new User());

        $form->number('uid', __('Uid'));
        $form->text('cate_ids', __('Cate ids'));
        $form->text('title', __('Title'));
        $form->text('imgurl', __('Imgurl'));
        $form->text('lat', __('Lat'));
        $form->text('lnt', __('Lnt'));
        $form->text('address', __('Address'));
        $form->text('address_detail', __('Address detail'));
        $form->text('linkname', __('Linkname'));
        $form->mobile('phone', __('Phone'));
        $form->text('start_time', __('Start time'));
        $form->text('end_time', __('End time'));
        $form->switch('status', __('Status'));
        $form->switch('merchant_use_status', __('Status'));

        return $form;
    }
}
